<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<div id ="user_edit_page" class="row-fluid" style="height: inherit;">
	<form id="user_edit_queryForm" class="form-horizontal"  style="overflow: auto; height: calc(100% - 70px);">
		<input type="hidden" name="userId" id="user_edit_userId" value="${user.id}">
		<div class="control-group">
			<label class="control-label" for="user_edit_username">用户名：</label>
			<div class="controls">
				<div class="input-append span12 required" >
					<input class="span11" type="text" title="用户名不可修改"  name="username" readonly value="${user.username}"
						   id="user_edit_username" placeholder="用户名">
				</div>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">性别：</label>
			<div class="controls">
				<label><input type="radio" id="user_edit_gender1" name="gender" value="1"  >男</label>
				<label><input type="radio" id="user_edit_gender2" name="gender" value="0"  >女</label>
			</div>
		</div>

		<div class="control-group">
			<label class="control-label" for="user_edit_initpwdbtn">密码初始化：</label>
			<div class="controls">
				<div class=" btn btn-danger" title="点击可以初始化用户密码" id="user_edit_initpwdbtn" >
					<i class="fa fa-refresh" aria-hidden="true"></i>&emsp;初始化
				</div>
			</div>
		</div>

		<div class="control-group">
			<label class="control-label" for="user_edit_name">真实姓名：</label>
			<div class="controls">
				<div class="input-append span12 required">
					<input class="span11" type="text" name="name" id="user_edit_name" value="${user.name}" placeholder="真实姓名" />
				</div>
			</div>
		</div>

		<div class="control-group">
			<label class="control-label">权限类别：</label>
			<div class="controls">
				<label><input type="radio" id="user_edit_usertype1" name="usertype" value="1"  >成品</label>
				<label><input type="radio" id="user_edit_usertype2" name="usertype" value="2"  >原材料</label>
			</div>
		</div>

		<div class="control-group">
			<label class="control-label" for="user_edit_roleId">所属角色：</label>
			<div class="controls">
				<input class="span11 select2_input" type="text" name="roleId" id="user_edit_roleId" />
				<input type="hidden" id="user_edit_roleno" value="${user.roleno}">
				<input type="hidden" id="user_edit_rolename" value="${user.rolename}">
			</div>
		</div>

		<div class="control-group">
			<label class="control-label" for="user_edit_phone">手机号码：</label>
			<div class="controls">
				<input class="span11" type="text" name="phone" id="user_edit_phone" value="${user.phone}" placeholder="手机号码" />
			</div>
		</div>

		<div class="control-group">
			<label class="control-label" for="user_edit_email">Email：</label>
			<div class="controls">
				<input class="span11" type="text" name="email" id="user_edit_email" value="${user.email}" placeholder="Email" />
			</div>
		</div>

		<div class="control-group">
			<label class="control-label" for="user_edit_remark">备注：</label>
			<div class="controls">
				<textarea class="span11" name="remark"  id="user_edit_remark" rows="3" cols="20"></textarea>
			</div>
		</div>

		<div class="control-group ">
			<label class="control-label" >权限范围：</label>
			<%--<div class="controls required">
				<c:forEach items="${factlist}" var="p">
					<input type = "checkbox" name="factoryCode" value="${p.CODE}"
						<c:forEach items="${factRelList}" varStatus="va"><c:if test="${factRelList[va.index]==p.CODE}">checked</c:if>
					</c:forEach>>${p.NAME}
					</input>
					</c:forEach>
			</div>--%>
			<div class="controls">
				<div class=" btn btn-danger" title="点击修改权限范围" id="user_edit_editrole" >
					<i class="fa fa-refresh" aria-hidden="true"></i>&emsp;修改权限范围
				</div>
			</div>
		</div>

	</form>
	<div class="form-actions" style="text-align: right;border-top: 0px;margin: 0px;">
		<span  class="savebtn btn btn-success">保存</span>
		<span  class="btn btn-danger">取消</span>
	</div>
</div>
<script type="text/javascript">
	var oriData;
	var _grid;
	var $queryWindow;  //查询窗口对象
	var user_add_openwindowtype = 1; //打开窗口类型：0新增，1修改
	var zTree;   //树形对象
	var selectTreeId = 0;   //存放选中的树节点id
	var usertype;
	//树的相关设置
	var setting = {
		check: {
			enable: true,
			chkStyle: "checkbox",
			chkboxType: {"Y":"p","N":"s"}
		},
		data: {
			simpleData: {
				enable: true
			}
		},
		edit: {
			enable: false,
			drag:{
				isCopy:false,
				isMove:false
			}
		},
		callback: {
			onAsyncSuccess: zTreeOnAsyncSuccess
		},
		async: {
			enable: true,
			url:context_path+"/user/getUserRoleByUserId",
			autoParam:["id"],
			otherParam: {"userId":$('#user_list_grid-table').jqGrid('getGridParam','selrow'),"type":null},
			type: "POST"
		},//异步加载数据
	};

	//ztree加载成功之后的回调函数
	function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
		zTree.expandAll(true);
	}

	$(window).triggerHandler('resize.jqGrid');

    $("#user_edit_queryForm input[type=radio]").uniform();
	var $queryWindow3 ;
	var $queryWindow4 ;
    var selectid = $('#user_list_grid-table').jqGrid('getGridParam','selrow');
    $("#user_edit_userId").val(selectid);
    $("#user_edit_remark").val('${user.remark}');

    if("${user.gender}"==='1'){
        $("input[type=radio][name=gender][value='1']").attr("checked",true).trigger("click");
    }else{
        $("input[type=radio][name=gender][value='0']").attr("checked",true).trigger("click");
    }

	if("${user.usertype}"==='1'){
		$("input[type=radio][name=usertype][value='1']").attr("checked",true).trigger("click");
	}else{
		$("input[type=radio][name=usertype][value='2']").attr("checked",true).trigger("click");
	}

    //部门下拉框初始化
    $("#user_edit_deptId").select2({
        placeholder: "选择部门",
        minimumInputLength:0,   //至少输入n个字符，才去加载数据
        allowClear: true,  //是否允许用户清除文本信息
        delay: 250,
        formatNoMatches:"没有结果",
        formatSearching:"搜索中...",
        formatAjaxError:"加载出错啦！",
        ajax : {
            url: context_path+"/dept/getDeptList",
            type:"POST",
            dataType : 'json',
            delay : 250,
            data: function (term,pageNo) {     //在查询时向服务器端传输的数据
                term = $.trim(term);
                return {
                    queryString: term,    //联动查询的字符
                    pageSize: 15,    //一次性加载的数据条数
                    pageNo:pageNo,    //页码
                    time:new Date()   //测试
                }
            },
            results: function (data,pageNo) {
                var res = data.result;
                if(res.length>0){   //如果没有查询到数据，将会返回空串
                    var more = (pageNo*15)<data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results:res,more:more
                    };
                }else{
                    return {
                        results:{}
                    };
                }
            },
            cache : true
        }

    });

    //所属角色
    $("#user_edit_roleId").select2({
        placeholder: "选择角色",
        minimumInputLength:0,   //至少输入n个字符，才去加载数据
        allowClear: true,  //是否允许用户清除文本信息
        delay: 250,
        formatNoMatches:"没有结果",
        formatSearching:"搜索中...",
        formatAjaxError:"加载出错啦！",
        ajax : {
            url: context_path+"/role/getRoleList",
            type:"POST",
            dataType : 'json',
            delay : 250,
            data: function (term,pageNo) {     //在查询时向服务器端传输的数据
                term = $.trim(term);
                return {
                    queryString: term,    //联动查询的字符
                    pageSize: 15,    //一次性加载的数据条数
                    pageNo:pageNo,    //页码
                    time:new Date()   //测试
                }
            },
            results: function (data,pageNo) {
                var res = data.result;
                if(res.length>0){   //如果没有查询到数据，将会返回空串
                    var more = (pageNo*15)<data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results:res,more:more
                    };
                }else{
                    return {
                        results:{}
                    };
                }
            },
            cache : true
        }

    });
    //初始化用户信息
    $.ajax({
        url:context_path+"/user/getUser?tm="+new Date(),
        type:"POST",
        data:{userId : selectid},
        dataType:"JSON",
        success:function(data){
            if(data){
                //将用户信息填充到form中
                for ( var attr in data) {
                    //文本框赋值
                    if(data[attr]){
                        if($("#user_edit_queryForm #"+attr)){
                            $("#user_edit_queryForm #"+attr).val(data[attr]);
                        }
                    }
                    if(attr === "gender"){
                    	//单选框赋值
                        $("input[type=radio][name=gender][value="+data[attr]+"]").attr("checked",true).trigger("click");
					}
					if(attr === "usertype"){
						//单选框赋值
						$("input[type=radio][name=usertype][value="+data[attr]+"]").attr("checked",true).trigger("click");
					}
                }
                //初始化部门下来框和角色下拉框的值
                initDept();
            }
        }
    });

    //表单校验
    $("#user_edit_queryForm").validate({
        rules:{
            "username" : {
                required:true,
                maxlength:32,
                remote:context_path+"/user/hasU.do?userId="+$('#user_edit_userId').val()
            },
            "name":{
                required:true,
                invalidChar:"'\"\\\\",
                maxlength:32
            },
            "phone":{
                mobile: true
            },
            "email":{
                email : true,
                maxlength:256
            },
            "roleId":{
                required:true
            },
            "remark":{
                maxlength:256
            },
            "deptId":{
                required:true
            },
            "factoryCode":{
                required:true
            }
        },
        messages:{
            "username":{
                remote:"您输入的用户名已经存在，请重新输入！"
            }
        },
        errorClass: "help-inline",
        errorElement: "span",
        highlight:function(element, errorClass, validClass) {
            $(element).parents('.control-group').addClass('error');
        },
        unhighlight: function(element, errorClass, validClass) {
            $(element).parents('.control-group').removeClass('error');
        }
    });

    //确定按钮点击事件
    $("#user_edit_page .btn-success").off("click").on("click", function(){
        //用户保存
        if($("#user_edit_queryForm").valid()){
            user_edit_saveUserInfo($("#user_edit_queryForm").serialize());
		}
    });

    //取消按钮点击事件
    $("#user_edit_page .btn-danger").off("click").on("click", function(){
        layer.close($queryWindow);
    });
    var ajaxStatus = 1;     //ajax请求状态：0不能请求，1可以请求
    //保存/修改用户信息
    function user_edit_saveUserInfo(bean){
        if(bean){
            if(ajaxStatus===0){
                layer.msg("保存中，请稍后...",{icon:2});
                return;
            }
            ajaxStatus = 0;
            $(".savebtn").attr("disabled","disabled");
            $.ajax({
                url:context_path+"/user/save?userFactoryIds=firstSave",
                type:"POST",
                data:bean,
                dataType:"JSON",
                success:function(data){
                    ajaxStatus = 1; //将标记设置为可请求
                    $(".savebtn").removeAttr("disabled");
                    if(data.result){
                        layer.msg("保存成功！",{icon:1});
                        //刷新用户列表
                        $("#user_list_grid-table").jqGrid('setGridParam',
                            {
                                postData: {queryJsonString:""} //发送数据
                            }
                        ).trigger("reloadGrid");
                        //关闭当前窗口
                        //关闭指定的窗口对象
                        layer.close($queryWindow);
                    }else{
                        layer.msg("保存失败，请稍后重试！",{icon:2});
                    }
                }
            });
        }else{
            layer.msg("出错啦！",{icon:2});
        }
    }

    //确定按钮点击事件
    $("#user_edit_page #user_edit_initpwdbtn").off("click").on("click", function(){
        //密码初始化
        layer.confirm('确定初始化密码？<br> 注：初始化的密码为123456。', /*显示的内容*/
            {
                shift: 6,
                moveType: 1, //拖拽风格，0是默认，1是传统拖动
                title:"操作提示",  /*弹出框标题*/
                icon: 3,      /*消息内容前面添加图标*/
                btn: ['确定', '取消']/*可以有多个按钮*/
            }, function(index, layero){
                $.ajax({
                    url:context_path+"/user/initUserPass",
                    type:"POST",
                    data:{userID : $("#user_edit_userId").val()},
                    dataType:"JSON",
                    success:function(data){
                        if(data){
                            layer.msg("操作成功！");
                            layer.close(index);
                        }else{
                            layer.msg("操作失败！");
                        }
                    }
                });
            }, function(index){
                //取消按钮的回调
                layer.close(index);
            });
    });

    if($("#user_edit_queryForm #user_edit_roleno").val()!=""){
        $("#user_edit_queryForm #user_edit_roleId").select2("data", {
            id: $("#user_edit_queryForm #user_edit_roleno").val(),
            text: $("#user_edit_queryForm #user_edit_rolename").val()
        });
    }

    //清空执行人多选框中的值
    function removeChoice2(){
        $("#user_edit_factoryCode .select2-choices").children(".select2-search-choice").remove();
        $("#user_edit_factoryCode").select2("val","");
        selectData = 0;
    }

	//确定按钮点击事件
	$("#user_edit_page #user_edit_showrole").off("click").on("click", function() {
		if ($("#user_edit_queryForm").valid()){
			user_add_openwindowtype = 1;
			selectid = $('#user_list_grid-table').jqGrid('getGridParam', 'selrow');
			layer.load(2);
			$.post(context_path + '/user/roleEdit', {}, function (str) {
				$queryWindow2 = layer.open({
					title: "权限编辑",
					type: 1,
					skin: "layui-layer-molv",
					area: "600px",
					shade: 0.6, //遮罩透明度
					moveType: 1, //拖拽风格，0是默认，1是传统拖动
					content: str,//注意，如果str是object，那么需要字符拼接。
					success: function (layero, index) {
						layer.closeAll('loading');
					}
				});
			});
		}
	});

	//确定按钮点击事件
	$("#user_edit_page #user_edit_editrole").off("click").on("click", function() {
		usertype = $('input:radio[name="usertype"]:checked').val();
		if ($("#user_edit_queryForm").valid()){
			user_add_openwindowtype = 1;
			selectid = $('#user_list_grid-table').jqGrid('getGridParam', 'selrow');
			user_list_pdd = $('#user_list_grid-table').jqGrid('getGridParam', 'selrow');
			layer.load(2);
			$.post(context_path + '/user/roleEdit', {}, function (str) {
				$queryWindow2 = layer.open({
					title: "权限编辑",
					type: 1,
					skin: "layui-layer-molv",
					area: "600px",
					shade: 0.6, //遮罩透明度
					moveType: 1, //拖拽风格，0是默认，1是传统拖动
					content: str,//注意，如果str是object，那么需要字符拼接。
					success: function (layero, index) {
						layer.closeAll('loading');
					}
				});
			});
		}
	});

</script>